<!--
 * @Author: your name
 * @Date: 2021-06-24 10:10:33
 * @LastEditTime: 2021-11-05 14:42:35
 * @LastEditors: Please set LastEditors
 * @Description: In User Settings Edit
 * @FilePath: \jinfengts\src\pages\Overview\Overview.vue
-->

<template>
  <div class="overView">
    <el-row>
      <el-col :span="24">
        <div class="announcement">
          <span class="announcementImg"></span>
          <div class="announcementContent">
            <marquee>{{ accountOutLine }}</marquee>
          </div>
          <span class="announcementExamine" @click="lookForAnnouncement">查看记录</span>
        </div>
      </el-col>
    </el-row>
    <el-row :gutter="30">
      <el-col :span="18">
        <StageDisplay />
      </el-col>
      <el-col :span="6">
        <MessageReminder
          @GetAllMessageListAsync="GetAllMessageListAsync"
          :userInfo="userInfo"
          :messageList="messageList"
        />
      </el-col>
    </el-row>

    <!-- 公告消息弹出框 -->
    <!-- 中止弹出框 -->
    <CommonDialog
      title="公告"
      width="75%"
      v-bind:dialogVisible="announcementDialogVisible"
      @on-change-dialogVisible="announcementChange"
      class="announcementDialog"
      top="10vh"
    >
      <template #body>
        <div class="messageReminderContent" v-for="(item, index) in messageOutput" :key="index">
          <div class="messaageContent">
            {{ item.announcementContent }}
          </div>
          <div class="messageFooter">
            <span>{{ item.createdAt | resolvingDate }}</span>
          </div>
        </div>
      </template>
      <template #dialog_footer>
        <el-button type="primary" class="submitReme" @click="closeAnnouncementDialog">关闭</el-button>
      </template>
    </CommonDialog>
  </div>
</template>
<script>
import StageDisplay from './components/stageDisplay'
import MessageReminder from './components/messageReminder.vue'
import CommonDialog from '@/components/commonDialog/commonDialog.vue'
import { OverView } from '@/api/overView/service'
const heartCheck = {
    timeout: 60 * 1000,
    timer: null,
    serverTimer: null,
    reset() {
        this.timer && clearTimeout(this.timer)
        this.serverTimer && clearTimeout(this.serverTimer)
    },
    start(ws) {
    // console.log('心跳检测')
        this.reset()
        this.timer = setTimeout(() => {
            // console.log('发送心跳,后端收到后，返回一个心跳消息')
            // onmessage拿到返回的心跳就说明连接正常
            ws.send(JSON.stringify({ heart: 1 }))
            this.serverTimer = setTimeout(() => {
                // 如果超过一定时间还没响应(响应后触发重置)，说明后端断开了
                ws.close()
            }, this.timeout)
        }, this.timeout)
    }
}

export default {
    name: '',
    components: {
        MessageReminder,
        StageDisplay,
        CommonDialog
    },
    props: {},
    data() {
        return {
            accountOutLine: '',
            dialog: false,
            loading: false,
            formLabelWidth: '100px',
            timer: null,

            messageOutput: [],
            // 接收弹出抽屉的数据
            DrawerForm: {
                taskId: '',
                productionName: '',
                versionNum: '',
                questionClassification: '',
                title: '',
                marketingPrograms: '',
                severity: '',
                severityDesc: ''
            },
            announcementDialogVisible: false,

            // 登录人信息
            userInfo: {},
            messageList: [],

            wsuri: `ws://${process.env.VUE_APP_BASE_WEBSCOKET}/websocket/`, // ws wss
            lockReconnect: false, // 连接失败不进行重连
            maxReconnect: 5, // 最大重连次数，若连接失败
            socket: null
        }
    },

    filters: {
    /**
     * @description: 时间格式过滤器
     * @param {Date} date 传入的时间值
     * @return {String} times 按照规则格式后的时间字符串
     */
        resolvingDate(date) {
            const d = new Date(date)
            const month = d.getMonth() + 1 < 10 ? '0' + (d.getMonth() + 1) : d.getMonth() + 1
            const day = d.getDate() < 10 ? '0' + d.getDate() : d.getDate()
            const hours = d.getHours() < 10 ? '0' + d.getHours() : d.getHours()
            const min = d.getMinutes() < 10 ? '0' + d.getMinutes() : d.getMinutes()
            const sec = d.getSeconds() < 10 ? '0' + d.getSeconds() : d.getSeconds()
            const times = d.getFullYear() + '-' + month + '-' + day + ' ' + hours + ':' + min + ':' + sec
            return times
        }
    },
    mounted() {
        this.getUserInfo()
        /* 连接成功--获得公告消息 */
        this.GetAllAnnouncementListAsync()
        this.GetAllMessageListAsync()
    },
    methods: {
    /**
     * @description: 公告弹出框弹出框传入子组件的更改
     * @param {Boolean} val 弹出框的显示或隐藏
     */
        announcementChange(val) {
            this.announcementDialogVisible = val
        },

        /**
     * @description: 查看 公告
     */
        lookForAnnouncement() {
            this.announcementDialogVisible = true
        },

        /**
     * @description: 关闭 公告展示
     */
        closeAnnouncementDialog() {
            this.announcementDialogVisible = false
        },

        /**
     * @description: 获取当前登陆人信息 初始化Webscoket通信方法
     */
        async getUserInfo() {
            try {
                const result = await OverView.UserGetUserInfoAsync()
                if (result.success) {
                    this.userInfo = result.data
                    // this.initWebSocket()
                }
            } catch (err) {
                console.log(err)
            }
        },

        /**
     * @description: Webscoket 断线重连
     */
        reconnect() {
            if (this.lockReconnect || this.maxReconnect <= 0) {
                return
            }
            setTimeout(() => {
                // this.maxReconnect-- // 不做限制 连不上一直重连
                // this.initWebSocket()
            }, 20 * 1000)
        },

        /**
     * @description: 初始化Webscoket通信
     */
        initWebSocket() {
            try {
                if ('WebSocket' in window) {
                    this.wsuri = this.wsuri + this.userInfo.id
                    this.socket = new WebSocket(this.wsuri)
                    this.wsuri = `ws://${process.env.VUE_APP_BASE_WEBSCOKET}/websocket/`
                } else {
                    console.log('您的浏览器不支持websocket')
                }

                this.socket.onopen = this.websocketonopen
                this.socket.onerror = this.websocketonerror
                this.socket.onmessage = this.websocketonmessage
                this.socket.onclose = this.websocketclose
            } catch (e) {
                this.reconnect()
            }
        },

        /**
     * @description: Webscoket通信连接成功
     */
        websocketonopen() {
            console.log('WebSocket连接成功', this.socket.readyState)

            heartCheck.start(this.socket)
        },

        /**
     * @description: Webscoket通信连接失败
     */
        websocketonerror() {
            this.reconnect()
        },

        /**
     * @description: Webscoket通信接收到消息
     */
        websocketonmessage() {
            // 消息获取成功，重置心跳
            heartCheck.start(this.socket)
        },

        /**
     * @description: Webscoket通信连接关闭
     * @param {Object} e 接收到的状态信息
     */
        websocketclose(e) {
            console.log('connection closed (' + e.code + ')')
            this.reconnect()
        },

        /**
     * @description: 客户端端向服务器发送信息
     */
        websocketsend() {
            const data = { answer: 'do something' }
            this.socket.send(JSON.stringify(data))
        },

        /**
     * @description: 获得当前登陆人所拥有的公告信息 汇总
     */
        async GetAllAnnouncementListAsync() {
            try {
                const result = await OverView.GetAllAnnouncementListAsync()
                if (result.success) {
                    this.messageOutput = result.data
                    if (this.messageOutput.length > 0) {
                        this.accountOutLine = this.messageOutput[0].announcementContent
                    }
                }
            } catch (err) {
                console.log(err)
            }
        },
        /**
     * @description: 获得当前登陆人所拥有的消息提醒 汇总
     */
        async GetAllMessageListAsync() {
            try {
                const result = await OverView.GetAllMessageListAsync()
                if (result.success) {
                    this.messageList = result.data
                    console.log('消息提醒信息', result.data)
                }
            } catch (err) {
                console.log(err)
            }
        }
    }
}
</script>

<style scoped lang="less">
.overView {
  width: 100%;
  height: 100%;
  // overflow: hidden;
  box-sizing: border-box;
  padding: 30px;
}
.el-form {
  padding: 0 30px;
}

::v-deep .el-form-item__label {
  font-size: 14px;
  font-family: Source Han Sans CN;
  font-weight: 400;
  color: #999999;
  text-align: left;
}

::v-deep .el-input__inner {
  width: 282px;
  height: 30px;
  background: #f4f5f8;
  border-radius: 5px;
}

/* 公告  */
.announcement {
  background: white;
  padding: 10px;
  height: 30px;
  margin-bottom: 15px;
  line-height: 30px;
  border-radius: 5px;
  display: flex;
  align-items: center;

  .announcementImg {
    display: inline-block;
    width: 25px;
    height: 25px;
    background: url('~@/assets/image/icon/notice.png') no-repeat;
    background-size: contain;
  }
  .announcementContent {
    width: 95%;
    font-size: 14px;
    height: 30px;
    font-weight: 500;
    max-width: 92%;
    color: #333;
    line-height: 30px;
    padding: 0 10px;
    position: relative;
    .rollInline {
      position: absolute;
    }
  }
  .announcementExamine {
    height: 100%;
    white-space: nowrap;
    line-height: 30px;
    font-size: 14px;
    color: #3579e0;
    font-weight: 500;
    cursor: pointer;
  }
}

::v-deep .announcementDialog .el-dialog__header {
  width: 100%;
}

::v-deep .announcementDialog .el-dialog__body {
  height: 595px;
  overflow: auto;
}

::v-deep .announcementDialog .el-dialog {
  height: 727px;
  box-sizing: border-box;
  border-radius: 5px;
}

.messageReminderContent {
  width: 100%;
  min-height: 175px;
  padding: 10px;
  background: #ffffff;
  box-sizing: border-box;
  border: 1px solid #ccc;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
  margin-bottom: 20px;
  user-select: none;

  .messaageContent {
    width: 100%;
    font-size: 16px;
    box-sizing: border-box;
    height: 144px;
  }
  .messageFooter {
    flex: 1;
    width: 100%;
    box-sizing: border-box;
    font-size: 17px;
    color: #666666;
    display: flex;
    align-items: center;
    justify-content: flex-end;
  }
}

::v-deep .el-carousel__arrow {
  display: none;
}
</style>
